package com.liuc.mybatis;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(4);
        for(int i=1; i<=6; i++){
            new Thread(() ->{
                try {
                    semaphore.acquire();//占用资源减一
                    System.out.println(Thread.currentThread().getName()+"\t抢占了车位");
                    TimeUnit.SECONDS.sleep(4);
                    System.out.println(Thread.currentThread().getName()+"\t离开了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//释放占用资源
                }
            },String.valueOf(i)).start();
        }
    }
}
